package com.platform.comm.web.results;

import lombok.Getter;
import lombok.Setter;

import java.util.Objects;
import java.util.function.Function;

/**
 * JSON result with response data
 * @author coder
 */
public class DataJsonResult<T> extends JsonResult {

    public DataJsonResult() {
        super();
    }

    public DataJsonResult(String msg) {
        super(msg);
    }

    @Getter
    @Setter
    protected T data;

    /**
     * 如果data字段不为null，则应用指定mapper函数给data。<br>
     * 字段code和message将原样复制
     *
     * @return 总返回一个新的DataJsonResult，原DataJsonResult不做修改
     */
    public <U> DataJsonResult<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        DataJsonResult<U> result = new DataJsonResult<>();
        result.copy(this);
        if (this.data != null) {
            result.data = mapper.apply(data);
        }
        return result;
    }

    public static <T> DataJsonResult<T> succeed(T data) {
        DataJsonResult<T> result = new DataJsonResult<>();
        result.setData(data);
        result.setMessage("操作成功");
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("DataJsonResult[");
        if (isSuccessful()) {
            sb.append("data=").append(data);
        } else {
            sb.append("code=").append(code).append(", message=").append(message);
        }
        sb.append("]");
        return sb.toString();
    }
}
